package com.admin.blog.service;

import com.admin.blog.dao.mapper.ArticleMapper;
import com.admin.blog.dao.mapper.FocusedMapper;
import com.admin.blog.dao.mapper.MessageMapper;
import com.admin.blog.dao.mapper.SysUserMapper;

import com.admin.blog.dao.pojo.Focused;
import com.admin.blog.dao.pojo.Message;

import com.admin.blog.vo.Result;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: YKH
 * Date: 202;
 * 3-06-08
 * Time: 14:00
 */
@Service
public class MessageService {
    @Autowired
    MessageMapper messageMapper;

    @Autowired
    ArticleMapper articleMapper;

    @Autowired
    SysUserMapper sysUserMapper;

    @Autowired
    FocusedMapper focusedMapper;


    /**
     * 推送消息给关注他的用户
     * @param
     * @return
     */
    @Transactional
    public Result addMessage(Long articleId, Long authorId) {
        List<Long> acceptIdList = new ArrayList<>();
        //先查关注表, 获取他的用户id列表
        LambdaQueryWrapper<Focused> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Focused::getFocusedId, authorId);
        List<Focused> focuseds = focusedMapper.selectList(queryWrapper);
        for (Focused focused:focuseds) {
            acceptIdList.add(focused.getLaunchId());
        }

        //构造消息, 往消息表插入
        for(int i=0; i< acceptIdList.size();i++){
            Message message = new Message();
            message.setArticleId( articleId );
            message.setAcceptUserId(acceptIdList.get(i));
            message.setLaunchUserId(authorId);
            message.setIsRead(0);
            message.setCreateDate(LocalDateTime.now());
            messageMapper.insert(message);
        }
        return Result.success("消息推送成功");
    }

}
